<template>
  <div id="app">
    <Navs v-if="Navsshow" />
    <router-view />
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import { GetSocketModule } from "@/store/modules/GetSocketData";
import { Navs } from "./components";
import { publicAPIModule } from "@/store/modules/public";
import "@/utils/sockjs.min.js";
import "@/utils/stomp.min.js";
import axios from "axios";
import reportVue from "./views/JointInspection/modules/InspectionMonitor/report.vue";
import date from "./utils/date";
import { log } from "three";

@Component({
  components: {
    Navs,
  },
})
export default class App extends Vue {
  public routername = "";
  public Navsshow = false;
  // 监听路由变化
  @Watch("$route", {
    //  immediate: true,
    deep: true,
  })
  public routechange(to: any, from: any) {
    if (from.path == "/login" && to.path == "/homepage/index") {
      this.pointTime = {};
    }
    if (to.name == null || to.name == "login") {
      (this as any).$notify.closeAll();
      this.Navsshow = false;
    } else {
      this.Navsshow = true;
    }
  }
  // 获取所有变电站Id
  get getterStationCodeArr() {
    return GetSocketModule.getterStationCodeArr;
  }
  // 监听变电站Id
  // @Watch("getterStationCodeArr")
  // private setSocketSubscribe(newData, oldData) {
  //   this.unSubscribeAll(oldData);
  //   this.subscribeAll(newData);
  // }
  mounted() {
    this.setTokensAliveTime();
    this.setTimer();
    this.sockjsInit();
  }
  beforeDestroy() {
    (this as any).$notify.closeAll();
    this.unSubscribeAll(this.getterStationCodeArr);
    this.clearTokensAlive();
    this.clearTimer();
  }
  sockjsInit() {
    let _this = this;
    let socket = new (window as any).SockJS((window as any).VUE_APP_SOCKETJS);
    let sc = (window as any).Stomp.over(socket);
    sc.debug = null;
    sc.connect({}, function (frame) {
      console.log("socket连接成功");
      sc.subscribe("pointer/data", function (res) {
        //  report/data
        let body = res.body;
        // console.log(res,888);

        if (body) {
          body = JSON.parse(body);
          body.forEach((v) => {});
          _this.socketData["pointer/data"] =
            _this.socketData["pointer/data"] || [];
          _this.socketData["pointer/data"].push(...body);
          // console.log(_this.socketData);
        }
      });
      console.log("333333333333socket连接成功");
      sc.subscribe("report/data", function (res) {
        //  report/data
        console.log(99999, res);
        let body = res.body;
        let alldw = GetSocketModule.getterAllAuxiliaryPointer;
        if (body) {
          _this.zdxjGjObj = JSON.parse(body);
        }
        alldw.forEach((e) => {
          if (_this.zdxjGjObj.stationCode == e.stationId) {
            _this.zdxjGjObj.stationName = e.stationName;
            _this.zdxjGjObj.id = new Date().getTime();
          }
        });
        console.log(_this.zdxjGjObj);
      });
    });
  }
  // 列表批量加入socket监听
  subscribeAll(data) {
    data.forEach((id) => {
      this.subscribe(id);
    });
  }

  // socket推送的数据
  socketData = {
    "pointer/data": [],
  };
  timer = null;
  // 设置数据推送定时器
  setTimer() {
    this.clearTimer();
    this.timer = window.setInterval(this.pushSocketData, 5000);
  }
  // 清除数据推送定时器
  clearTimer() {
    if (this.timer) {
      window.clearInterval(this.timer);
      this.timer = null;
    }
  }
  // 推送socket数据到台账
  pushSocketData() {
    for (let key in this.socketData) {
      let arr = this.socketData[key];
      let obj = {
        id: key,
        list: arr,
      };
      GetSocketModule.setSocketObj(obj);
      this.socketData[key] = [];
    }
  }
  // 加入socket监听
  subscribe(id) {
    let _this = this;
    this.$socket.emit("joinRoom", { room: id }, function (res: any) {
      console.log(id + ":房间加入成功");
      (_this as any).sockets.subscribe(id, (res: any) => {
        _this.socketData[id] = _this.socketData[id] || [];
        _this.socketData[id].push(...res);
      });
    });
  }
  // 解除所有socket监听
  unSubscribeAll(data) {
    data.forEach((id) => {
      this.unSubscribe(id);
    });
  }
  // 解除单个socket监听
  unSubscribe(id) {
    (this as any).sockets.unsubscribe(id);
    this.$socket.emit("leaveRoom", { room: id }, function () {
      console.log(id + ":房间离开成功");
    });
  }
  TokensAliveTime: any = null;
  // 视频平台登录状态持续激定时器
  setTokensAliveTime() {
    this.getTokensAlive();
    if (this.TokensAliveTime) {
      this.clearTokensAlive();
    }
    this.TokensAliveTime = window.setInterval(this.getTokensAlive, 20000);
  }
  // 视频平台登录状态持续激
  getTokensAlive() {
    (this as any).$services
      .getTokensAlive()
      .then((result: any) => {
        // console.log(result);
      })
      .catch((err: object) => {
        console.log(err);
      });
  }
  // 清空视频平台登录状态持续激定时器
  clearTokensAlive() {
    if (this.TokensAliveTime) {
      window.clearInterval(this.TokensAliveTime);
      this.TokensAliveTime = null;
    }
  }
  getHtml() {
    let getGjPoint: any = this.getGjPoint || {};
    var obj: any = {};

    let time = getGjPoint.time || "";
    let html = `<div class='gaoji-container'>
    <div class='inner startbox'>
      <div>${time.slice(0, 10)}</div>
      <div>${time.slice(10, 20)}</div>
      <div>${getGjPoint.stationName}</div>
    </div>
    <div class='inner startbox'>
      <div title='${getGjPoint.message || ""}'>${getGjPoint.message || ""}</div>
    </div>
    </div>`;
    return html;
  }
  getHtml1() {
    let zdxjGjObj: any = this.zdxjGjObj || {};
    function format(Date) {
      var y = Date.getFullYear();
      var m = Date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = Date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = Date.getHours();
      h = h < 10 ? "0" + h : h;
      var f = Date.getMinutes();
      f = f < 10 ? "0" + f : f;
      var s = Date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + m + "-" + d + "\xa0" + h + ":" + f + ":" + s;
    }
    var nowDate = new Date();
    let html = `<div class='gaoji-container'>
    <div class='inner startbox'>
    <span class='iconfont iconlaba'>
        <audio autoplay  src="/music/messageAudio.mp3"></audio>
      </span>
      <div>${format(nowDate)}</div>
      <div>${zdxjGjObj.stationName}</div>
    </div>
    <div class='inner startbox'>
      <div title='${zdxjGjObj.resultInfo || ""}'>${
      zdxjGjObj.resultInfo || ""
    }</div>
    </div>
    </div>`;
    return html;
  }
  //put("stationCode",stationID);
  // put("videoIp",videoInfo.IP);
  // put("videoCode",videoInfo.VideoCode);
  // put("resultInfo",info.resultInfo);
  // put("type","RealTimeAdvAnalyzeResultForGK");
  zdxjGjObj: any = {
    // jcsj:'2021-02-26 16:55:56',
    // StationID:"1500280271",
    // xsnr:'#999',
    // jgzsfs:'#888',
  };
  //自动巡检 告警数据
  // get zdxjGj(){
  //   let obj:any={}

  //   setTimeout(()=>{
  //     obj.time='2021-02-25 18:55:56'
  //     obj.stationName='220kV天平变电站999'
  //     obj.message="#999"
  //     obj.id="1500280271"
  //     obj.timeNum = new Date(obj.time).getTime();

  //   },2000)
  //   return obj
  // }
  //※※※※※※※获取所有的点位
  get getGjPoint() {
    let getterAllAuxiliaryPointer = GetSocketModule.getterAllAuxiliaryPointer;
    // console.log(9898, getterAllAuxiliaryPointer);
    // let allDw = GetSocketModule.getterAllAuxiliaryPointer;
    // getterAllAuxiliaryPointer.forEach((e) => {
    //   if (e.stationCode == "1500000001") {
    //     console.log(e);
    //   }
    // });

    let time = 0;
    let obj: any = {};
    getterAllAuxiliaryPointer.forEach((v) => {
      if (v.isGj && v.isOpen === "1" && v.message && v.time) {
        console.log(v);

        let timeNum = new Date(v.time).getTime();
        console.log(timeNum);
        // console.log(time);

        if (timeNum > time) {
          time = timeNum;
          obj = v;
        }
      }
    });
    // console.log('obj',obj);

    var aa = this.zdxjGjObj;

    var pointerTime = new Date(obj.time).getTime();
    var zdxjjGtime = new Date(aa.jcsj).getTime();
    if (zdxjjGtime > pointerTime) {
      let stationList = publicAPIModule.SubstationList || [];
      var stationName = stationList.filter((v) => {
        return v.code == aa.StationID;
      });
      obj = {
        time: aa.jcsj,
        // stationName:stationName[0].name || '',
        message: aa.xsnr + " " + aa.jgzsfs,
        // id:aa.StationID || ''
      };
      if (stationName && stationName.length > 0) {
        obj.stationName = stationName[0].name;
        obj.id = aa.StationID;
      }
      console.log("--------");
    }
    // console.log(obj);

    return obj;
  }
  addInframe() {
    // let el-picker-panel el-date-picker el-popper
    window.setTimeout(() => {
      let pickerArr = document.querySelectorAll(".el-notification");
      pickerArr.forEach((item) => {
        let width = item.clientWidth;
        let height = item.clientHeight;
        let iframe: any = item.querySelector("iframe");
        if (!iframe) {
          iframe = document.createElement("iframe");
          item.appendChild(iframe);
        }
        iframe.style.width = width + "px";
        iframe.style.height = height + "px";
        iframe.style.position = "absolute";
        iframe.style.top = "0px";
        iframe.style.left = "0px";
        iframe.style.zIndex = 1;
        iframe.style.border = "none";
        iframe.style.pointerEvents = "none";
        iframe.frameborder = 0;
      });
    }, 100);
  }
  pointTime = {};
  pointTime1 = {};
  setPointTime(point) {
    // console.log(point);

    let getGjPoint = point || {};
    let time = new Date().getTime();
    let id = getGjPoint.id || "";
    this.pointTime[id] = time;
  }
  setPointTime1(point) {
    // console.log(point);

    let getGjPoint1 = point || {};
    let time = new Date().getTime();
    let id = getGjPoint1.id || "";
    this.pointTime1[id] = time;
  }
  testShowPoint1(point) {
    let id = point.id || "";
    if (!id) {
      return false;
    }
    // console.log(this.pointTime);

    let pointTime = this.pointTime1[id] || 0;
    let now = new Date().getTime();
    // console.log(now);
    // console.log(pointTime);

    if (now - pointTime > 30 * 60 * 1000) {
      return true;
    } else {
      return false;
    }
  }
  testShowPoint(point) {
    let id = point.id || "";
    if (!id) {
      return false;
    }
    // console.log(this.pointTime);

    let pointTime = this.pointTime[id] || 0;
    let now = new Date().getTime();
    // console.log(now);
    // console.log(pointTime);

    if (now - pointTime > 30 * 60 * 1000) {
      return true;
    } else {
      return false;
    }
  }
  isAddTime = true;
  @Watch("zdxjGjObj")
  showM(val) {
    let test = this.testShowPoint1(val);
    // console.log(test);

    if (!test) {
      return false;
    }
    let that = this;
    this.isAddTime = false;
    (this as any).$notify.closeAll();
    this.isAddTime = true;
    let html11 = this.getHtml1();
    this.addInframe();
    if (
      this.$route.path != "/login" &&
      val.type == "RealTimeAdvAnalyzeResultForGK"
    ) {
      this.$notify({
        title: "",
        dangerouslyUseHTMLString: true,
        position: "bottom-left",
        duration: 0,
        offset: 5,
        customClass: "gaoji",
        message: html11,
        onClose: () => {
          if (that.isAddTime) {
            // console.log(val);

            that.setPointTime1(val);
          }
        },
        onClick: () => {
          (this as any).$notify.closeAll();
          that.setPointTime1(val);
          that.$router.push({
            path: "/operationmonitor/index",
          });
        },
      });
    }
  }
  @Watch("getGjPoint")
  showMessage(val) {
    // console.log("展示点位信息", val);
    let test = this.testShowPoint(val);
    // console.log(test);

    if (!test) {
      return false;
    }
    let that = this;
    this.isAddTime = false;
    (this as any).$notify.closeAll();
    this.isAddTime = true;
    let getHtml = this.getHtml();
    // console.log(getHtml);

    this.addInframe();
    this.$notify({
      title: "",
      dangerouslyUseHTMLString: true,
      position: "bottom-left",
      duration: 0,
      offset: 5,
      customClass: "gaoji",
      message: getHtml,
      onClose: () => {
        if (that.isAddTime) {
          // console.log(val);

          that.setPointTime(val);
        }
      },
      onClick: () => {
        that.setPointTime(val);
        that.$router.push({
          path: "/operationmonitor/index",
        });
      },
    });
    // (this as any).$services
    //   .getUserPhone()
    //   .then((result: any) => {
    //     console.log(result);
    //     if (result.code == 200) {
    //       let smsAccount = publicAPIModule.smsAccount;
    //       console.log(smsAccount);
    //       let zd = result.data.map(v=>v.VALUE)
    //       let userinf:any=localStorage.getItem('userinf')
    //       userinf=JSON.parse(userinf)
    //       let username=userinf.username
    //     let msg=`告警时间:${val.time},所属变电站:${val.stationName},告警内容:${val.message},报告人:${username}。`
    //       let params = {
    //         account: smsAccount.account,
    //         password: smsAccount.password,
    //         businessType: "523456",
    //         msg,
    //         mobile: zd.join(","),
    //       };
    //       let url = `${process.env.VUE_APP_SMSURL}/send/api/sms`;
    //       // axios.post(url, params).then();title blueTitleStyle
    //     }
    //   })
    //   .catch((err: object) => {
    //     console.log(err);
    //   });
  }
}
</script>
<style lang="scss">
html,
body {
  width: 100vw;
  height: 100vh;
  overflow: hidden;

  .gaoji {
    background: rgba(15, 81, 81, 0.8);
    padding: 0.1rem 0.2rem 0.1rem 0.1rem;
    border-radius: 4px;
    border: 1px solid rgba(43, 143, 143, 1);
    width: 4rem;
    .el-notification__closeBtn {
      top: 0.1rem;
      right: 0.1rem;
    }
    .gaoji-container {
      cursor: pointer;
      .inner {
        > div {
          width: auto;
          margin-right: 0.16rem;
        }
      }
    }
  }
}
#app {
  width: 100%;
  height: 100%;
  color: #fff;
  background-image: url("./assets/img/HomePage/homebg.png");
  background-size: 100% 100%;
  background-position: center;
  .router-view {
    padding-top: 0.88rem;
    height: 100%;
    width: 100%;
  }
  .Navs {
    height: 0.88rem;
    position: absolute;
    top: 0px;
    z-index: 1024;
  }
}
// .el-notification {
//   border: none;
//   background: #2c89a3 !important;
// }
</style>
